package org.lex.ftplist.core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.DocumentException;
import org.lex.collection.tree.ITreeNode;
import org.lex.ftplist.core.conf.ConfLoader;
import org.lex.ftplist.util.Conf;
import org.lex.ftplist.util.Ids;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CacheService {
	private static final CacheService INSTANCE = new CacheService();

	public static CacheService getInstance() {
		return INSTANCE;
	}

	public void store(FtpUrl ftpUrl, ITreeNode root) throws IOException {
		Date date = new Date();
		File dir = Conf.getCacheDirectory();
		File indexFile = Ids.generateUniqueFileName(dir, ftpUrl.host, INDEX_SUFFIX, date);
		Index index = new Index(ftpUrl, date);

		ConfLoader.storeIndeies(index, indexFile);
		File ftpFile = Ids.generateUniqueFileName(dir, ftpUrl.host, FTP_SUFFIX, date);

		ConfLoader.storeFTPList(root, ftpFile);
		this.indexList.put(index, indexFile);
	}

	public ITreeNode load(Index index) throws IOException, DocumentException {
		File indexFile = indexList.get(index);
		String name = indexFile.getName();
		name = name.substring(0, name.length() - INDEX_SUFFIX.length());
		name = name + FTP_SUFFIX;
		File ftpFile = new File(indexFile.getParentFile(), name);
		log.info("index=[" + indexFile + "] ftp=[" + ftpFile + "]");
		return ConfLoader.loadFTPList(ftpFile);
	}

	public Collection<Index> getIndexList() {
		return indexList.keySet();
	}

	private static final String INDEX_SUFFIX = ".index";
	private static final String FTP_SUFFIX = ".ftplist";
	private Map<Index, File> indexList = new HashMap<Index, File>();
	private Logger log = LoggerFactory.getLogger(CacheService.class);

	private CacheService() {
		try {
			ConfLoader.loadIndeies(indexList);
		} catch (FileNotFoundException e) {
			log.error("", e);
		} catch (UnsupportedEncodingException e) {
			log.error("", e);
		} catch (IOException e) {
			log.error("", e);
		} catch (DocumentException e) {
			log.error("", e);
		}
		log.info(indexList.size() + " index loaded");
	}
}
